﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataModels;
using FKDatabase;

namespace Test_Operator_Platform.UI
{
    public partial class FrmEditDebugPro : Form
    {
        bool edited;
        string serialNumber;
        string partNumber;
        string tResult;
        public FrmEditDebugPro(bool edited, string sn, string pn, string result)
        {
            InitializeComponent();

            this.edited = edited;
            this.serialNumber = sn;
            this.partNumber = pn;
            this.tResult = result;
        }

        private void FrmEditDebugPro_Load(object sender, EventArgs e)
        {
            var partNumbers = Database.GetDisTestPlan();
            this.cb_partNumber.Items.Clear();
            foreach (var pn in partNumbers)
            {
                this.cb_partNumber.Items.Add(pn.TestPlan);
            }
            if (this.cb_partNumber.Items.Count > 0)
            {
                this.cb_partNumber.SelectedIndex = 0;
            }

            this.cbResult.Items.Add("PASS");
            this.cbResult.Items.Add("FAIL");

            if (this.edited)
            {
                this.cb_partNumber.Text = this.partNumber;
                this.tbSN.Text = this.serialNumber;
                this.cbResult.Text = this.tResult;
            }
            this.btnCancel.Click += BtnCancel_Click;
            this.btnOK.Click += BtnOK_Click;
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbSN.Text.Trim()))
            {
                MessageBox.Show("样件条码不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(this.cbResult.Text.Trim()))
            {
                MessageBox.Show("样件结果不能为空！");
                return;
            }
            TbDebugProduct dp = new TbDebugProduct();
            dp.PartNumber = this.cb_partNumber.Text;
            dp.SerialNumber = this.tbSN.Text.Trim();
            dp.TestResult = this.cbResult.Text;

            if (!this.edited)
            {
                if (Database.DebugProductExist(this.tbSN.Text.Trim(), this.cb_partNumber.Text))
                {
                    MessageBox.Show("样件已经存在！");
                }
                Database.AddDebugProduct(dp);
            }
            else
            {
                Database.UpdateDebugProduct(dp, this.serialNumber, this.partNumber);
            }
            this.Close();
            this.DialogResult = DialogResult.OK;
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
